import React, { Component } from 'react'
import { Text, StyleSheet, View, TouchableOpacity, TouchableHighlight,  Image, ScrollView, Dimensions, FlatList } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Loading from '../../components/Loading'

export default class index extends Component {
  constructor(props) {
    super(props)

    this.state = {
      types: [
        {key: 'top', title: '头条'},
        {key: 'shehui', title: '社会'},
        {key: 'guonei', title: '国内'},
        {key: 'guoji', title: '国际'},
        {key: 'yule', title: '娱乐'},
        {key: 'tiyu', title: '体育'},
        {key: 'junshi', title:  '军事'},
        {key: 'keji', title: '科技'},
        {key: 'caijing', title: '财经'},
        {key: 'shishang', title: '时尚'}
      ],
      type: 'top', // 默认新闻分类
      initNumber: 0, // 初始选中的新闻分类
      list: [],
    }
  }

  componentDidMount() {
    // 获取新闻数据
    this.getNewsList()
  }

  getNewsList = () => {
    const key = "6d7ee8d88bd4fb137f5d20ce7066a700"
    const type = this.state.type
    const url = `http://v.juhe.cn/toutiao/index?key=${key}&type=${type}`
    fetch(url)
      .then(response => {
        console.log(222, response)
        return response.json()
      })
      .then(responseJson => {
        // console.log('444', responseJson.result.data);
        //把请求下来的数据更新到 state中
        if (responseJson.error_code === 0) {
          this.setState({
            list: responseJson.result.data,
          });
        } else {
          // todo 处理返回失败的场景
          alert('获取新闻失败')
        }
      })
      .catch(error => {
        console.error(error);
      });
  }

  newsItem = ({index, item}) => {
    if (item.thumbnail_pic_s02 && item.thumbnail_pic_s03) {
      return this.newsItemThreeImages({index, item})
    } else {
      return this.newsItemOneImage({index, item})
    }
  }

  newsItemOneImage = ({index, item}) => {
    const { navigate } = this.props.navigation;

    return (
      <TouchableOpacity
        onPress={() => navigate('NewsDetail', {
          uniquekey: item.uniquekey,
          url: item.url,
          title: item.title
        })}
        style={{marginVertical: 5}}
      >
        <View style={{flexDirection: 'row', justifyContent: "space-between", alignItems: 'center', marginVertical: 10}}>
          <View style={{flexDirection: 'column', justifyContent: "space-between", width: Dimensions.get('window').width * 2/3 - 20 }}>
            <Text 
                style={{paddingHorizontal: 10, fontSize: 18, width: Dimensions.get('window').width * 2/3, marginBottom: 20}}
                numberOfLines={2}
                ellipsizeMode="tail"
            >
              {item.title}
            </Text>
            <View style={{flexDirection: 'row', justifyContent: 'space-between',paddingHorizontal: 10}}>
              <Text style={[styles.newsItemMeta, {width: Dimensions.get('window').width * 2/3 - 50}]} ellipsizeMode="tail" numberOfLines={1}>{item.date}  {item.author_name}</Text>
              <Ionicons name={'heart-outline'} size={18}  />
            </View>
          </View>

          <Image
                source={{uri: item.thumbnail_pic_s}}
                style={{
                  width: Dimensions.get('window').width/3,
                  height: 80,
                  marginVertical: 5,
                  marginHorizontal: 10
              }}
          />
        </View>
      </TouchableOpacity>
    );
  }

  // 展示新闻列表中的一条新闻
  newsItemThreeImages = ({index, item}) => {
    // console.log('item', item)
    const { navigate } = this.props.navigation;

    return (
      <TouchableOpacity
        onPress={() => navigate('NewsDetail', {
          uniquekey: item.uniquekey,
          url: item.url,
          title: item.title
        })}
        style={{marginVertical: 5}}
      >
        <View style={[styles.newsItemContainer]}>
          <Text 
              style={[styles.newsItemHeader]}
              numberOfLines={2}
              ellipsizeMode="tail"
          >
            {item.title}
          </Text>

          <View>
            <View style={[styles.newsItemImageContainer]}>
              <Image
                  source={{uri: item.thumbnail_pic_s}}
                  style={[styles.newsItemImage]}
              />
              <Image
                  source={{uri: item.thumbnail_pic_s02}}
                  style={[styles.newsItemImage]}
              />
              <Image
                  source={{uri: item.thumbnail_pic_s03}}
                  style={[styles.newsItemImage]}
              />
            </View>
          </View>

          <View style={[styles.newsItemFooter]}>
            <Text style={[styles.newsItemMeta]}>{item.date}  {item.author_name}</Text>
            <Ionicons name={'heart-outline'} size={18}  />
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  newsType = ({index, item}) => {
    console.log('newsType', index, item)
    let isActive = item.key == this.state.type
    return (
      <TouchableHighlight
        onPress={() => {
          // alert(item.key)
          this.setState({
            type: item.key,
            initNumber: index
          }, () => {
            this.getNewsList()
          })
        }}
      >
        <View  style={{width: 65, height: 46, padding: 10, backgroundColor: isActive ? '#dfb' : 'white' }}  >
          <Text
            style={{
              fontSize: 18,
              fontWeight: 'bold',
              color: isActive ? 'red' : '#333',
              textAlign:'center'
            }}
          >{item.title}</Text>
        </View>
      </TouchableHighlight>
    )
  }
  
  render() {
    return (
      <>
        {
          this.state.list.length 
          ? 
          <FlatList
          ListHeaderComponent={() => {
            // return <ScrollView horizontal={true}>{this.state.types.map((item, index) => {
            //   // console.log('ttt', item)
            //   return  this.newsType({index, item})
            // })}</ScrollView>
            
            return <FlatList
              data={this.state.types}
              renderItem={this.newsType}
              keyExtractor={item => item.key}
              horizontal={true}
              initialScrollIndex={this.state.initNumber}
              // style={{position: 'fixed', top: 100}}
            />
          }}
          stickyHeaderIndices={[0]}
          initialScrollIndex={0}
          data={this.state.list}
          renderItem={this.newsItem}
          keyExtractor={item => item.uniquekey}
          ItemSeparatorComponent={() => {
            return <View style={{borderBottomWidth: 1, borderBottomColor: '#ccc', marginHorizontal: 10}}></View>;
          }}
          // onEndReached={this._onEndReached}
          ListFooterComponent={() => {
            return <Text style={{fontSize: 20, textAlign: 'center', marginVertical: 40}}>---- 没有更多了 ----</Text>
          }}
        />
        :
        <Loading />
      }
      </>
    )
  }
}

const styles = StyleSheet.create({
  // container: {
  //   margin: 10,
  //   flexDirection: 'column',
  //   justifyContent: 'flex-start'
  // },
  newsItemContainer: {
    margin: 10
  },
  newsItemHeader: {
    fontSize: 18,
    width: Dimensions.get('window').width - 20,
  },
  newsItemImageContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  newsItemImage: {
    width: Dimensions.get('window').width/3-20,
    height: 80,
    marginVertical: 10
  },

  newsItemFooter: {
    // flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%'
    // flexWrap: 'wrap'
  },
  
  newsItemMeta: {
    fontSize: 13
  }
})
